<template>
  <div class="markdown-content" v-html="renderedContent"></div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  content: {
    type: String,
    default: ''
  }
})

const renderedContent = computed(() => {
  let html = props.content

  // 修复流式传输中可能被分割的Markdown格式
  // 修复被分割的加粗格式 
  html = html.replace(/\*\*([^*]*?)\n([^*]*?)\*\*/g, '**$1$2**')
  html = html.replace(/__([^_]*?)\n([^_]*?)__/g, '__$1$2__')
  
  // 修复跨行的加粗格式（去掉中间的换行）
  html = html.replace(/\*\*([^*]*?)\*\*/gs, (match, content) => {
    const cleanContent = content.replace(/\n/g, ' ')
    return `**${cleanContent}**`
  })

  // 首先处理代码块（必须在其他处理之前，避免其内容被误处理）
  html = html.replace(/```([\s\S]*?)```/g, '<pre class="markdown-code-block"><code>$1</code></pre>')

  // 处理行内代码
  html = html.replace(/`([^`\n]+)`/g, '<code class="inline-code">$1</code>')

  // 处理标题（按级别从高到低处理，避免冲突）
  html = html.replace(/^### (.*$)/gm, '<h3 class="markdown-h3">$1</h3>')
  html = html.replace(/^## (.*$)/gm, '<h2 class="markdown-h2">$1</h2>')
  html = html.replace(/^# (.*$)/gm, '<h1 class="markdown-h1">$1</h1>')

  // 处理加粗：更灵活的匹配，处理跨行和不完整的情况
  // 匹配 **text** 格式，允许内容跨行
  html = html.replace(/\*\*([^*]+?)\*\*/gs, '<strong>$1</strong>')
  // 匹配 __text__ 格式
  html = html.replace(/__([^_]+?)__/gs, '<strong>$1</strong>')

  // 处理斜体：在加粗之后处理，避免冲突
  html = html.replace(/(?<!\*)\*([^*\n]+?)\*(?!\*)/g, '<em>$1</em>')
  html = html.replace(/(?<!_)_([^_\n]+?)_(?!_)/g, '<em>$1</em>')

  // 处理列表 - 改进算法，更好地处理流式数据
  const lines = html.split('\n')
  const processedLines = []
  let currentList = null
  let currentListType = null

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    
    // 检查是否是无序列表项
    const unorderedMatch = line.match(/^[-*+]\s+(.+)$/)
    // 检查是否是有序列表项
    const orderedMatch = line.match(/^\d+\.\s+(.+)$/)
    
    if (unorderedMatch) {
      if (currentListType !== 'ul') {
        // 结束当前列表，开始新的无序列表
        if (currentList) {
          processedLines.push(`</${currentListType}>`)
        }
        processedLines.push('<ul class="markdown-ul">')
        currentListType = 'ul'
        currentList = true
      }
      processedLines.push(`<li class="markdown-ul-item">${unorderedMatch[1]}</li>`)
    } else if (orderedMatch) {
      if (currentListType !== 'ol') {
        // 结束当前列表，开始新的有序列表
        if (currentList) {
          processedLines.push(`</${currentListType}>`)
        }
        processedLines.push('<ol class="markdown-ol">')
        currentListType = 'ol'
        currentList = true
      }
      processedLines.push(`<li class="markdown-ol-item">${orderedMatch[1]}</li>`)
    } else {
      // 非列表项，结束当前列表
      if (currentList) {
        processedLines.push(`</${currentListType}>`)
        currentList = null
        currentListType = null
      }
      processedLines.push(line)
    }
  }

  // 如果文件末尾还有未结束的列表
  if (currentList) {
    processedLines.push(`</${currentListType}>`)
  }

  html = processedLines.join('\n')

  // 处理引用
  html = html.replace(/^>\s*(.+)$/gm, '<blockquote class="markdown-quote">$1</blockquote>')

  // 处理分割线
  html = html.replace(/^-{3,}$/gm, '<hr class="markdown-hr">')
  html = html.replace(/^\*{3,}$/gm, '<hr class="markdown-hr">')

  // 最后处理换行（保留必要的换行，但不破坏HTML结构）
  html = html.replace(/\n(?![<]|$)/g, '<br>')
  
  return html
})
</script>

<style scoped>
.markdown-content {
  line-height: 1.6;
  word-wrap: break-word;
}

/* 标题样式 */
.markdown-content :deep(.markdown-h1) {
  font-size: 1.5em;
  font-weight: bold;
  margin: 16px 0 8px 0;
  color: #2d3748;
  border-bottom: 2px solid #e2e8f0;
  padding-bottom: 4px;
}

.markdown-content :deep(.markdown-h2) {
  font-size: 1.3em;
  font-weight: bold;
  margin: 14px 0 6px 0;
  color: #2d3748;
}

.markdown-content :deep(.markdown-h3) {
  font-size: 1.1em;
  font-weight: bold;
  margin: 12px 0 4px 0;
  color: #4a5568;
}

/* 加粗和斜体 */
.markdown-content :deep(strong) {
  font-weight: bold;
  color: #2d3748;
}

.markdown-content :deep(em) {
  font-style: italic;
  color: #4a5568;
}

/* 列表样式 */
.markdown-content :deep(.markdown-ul) {
  margin: 8px 0;
  padding-left: 20px;
  list-style: none;
}

.markdown-content :deep(.markdown-ul-item) {
  position: relative;
  margin: 4px 0;
  padding-left: 16px;
}

.markdown-content :deep(.markdown-ul-item):before {
  content: "•";
  position: absolute;
  left: 0;
  color: #4299e1;
  font-weight: bold;
}

.markdown-content :deep(.markdown-ol) {
  margin: 8px 0;
  padding-left: 20px;
  counter-reset: markdown-counter;
}

.markdown-content :deep(.markdown-ol-item) {
  position: relative;
  margin: 4px 0;
  padding-left: 20px;
  counter-increment: markdown-counter;
}

.markdown-content :deep(.markdown-ol-item):before {
  content: counter(markdown-counter) ".";
  position: absolute;
  left: 0;
  color: #4299e1;
  font-weight: bold;
}

/* 代码样式 */
.markdown-content :deep(.inline-code) {
  background-color: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 3px;
  padding: 2px 4px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
  color: #e53e3e;
}

.markdown-content :deep(.markdown-code-block) {
  background-color: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  margin: 8px 0;
  overflow-x: auto;
}

.markdown-content :deep(.markdown-code-block code) {
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
  color: #2d3748;
  white-space: pre;
}

/* 引用样式 */
.markdown-content :deep(.markdown-quote) {
  border-left: 4px solid #4299e1;
  background-color: #f7fafc;
  padding: 8px 12px;
  margin: 8px 0;
  font-style: italic;
  color: #4a5568;
}

/* 分割线 */
.markdown-content :deep(.markdown-hr) {
  border: none;
  border-top: 2px solid #e2e8f0;
  margin: 16px 0;
}
</style> 